<template>
  <div>
    <el-card class="search-form">
      <el-form :model="formData" label-width="100px" ref="formRef" inline>
        <el-form-item label="品牌名称">
          <el-input
            v-model.trim="formData.tmName"
            clearable
            placeholder="请输入"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSearch">搜索</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin-top: 14px">
      <el-button type="primary" size="default" icon="Plus" @click="onAdd">
        新增品牌
      </el-button>
      <el-table style="margin: 10px 0px" border :data="tableData">
        <el-table-column
          label="序号"
          width="80px"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column
          label="品牌名称"
          prop="tmName"
          align="center"
        ></el-table-column>
        <el-table-column label="品牌LOGO" align="center">
          <template #="{ row }">
            <img :src="row.logologoUrl" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #="{ row }">
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="onEdit(row)"
            ></el-button>
            <el-popconfirm
              :title="`您确定要删除${row.tmName}?`"
              width="250px"
              icon="Delete"
              @confirm="onDelete(row.id)"
            >
              <template #reference>
                <el-button
                  type="primary"
                  size="small"
                  icon="Delete"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizeChange"
        @current-change="getTableData"
        :pager-count="9"
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 6, 9, 12]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
      />
    </el-card>

    <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="500px"
      :before-close="handleClose"
    >
      <el-form
        :model="formDlgData"
        label-width="100px"
        :rules="formRules"
        ref="formDlgRef"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input
            v-model.trim="formDlgData.tmName"
            clearable
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="品牌图片" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="formDlgData.logoUrl"
              :src="formDlgData.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitDlg()">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from '@/api/product/trademark/trademark'
import {
  Records,
  TradeMarkResponseData,
  TradeMark,
} from '@/api/product/trademark/type'
import {
  ElNotification,
  UploadProps,
  UploadUserFile,
  ElMessage,
} from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
interface RuleForm {
  tmName: string
  logoUrl: string
}
const formRef = ref()
const formData = reactive({
  tmName: '',
  id: '',
  logoUrl: '',
})

// const formDlgRef = ref<FormInstance>()
const formDlgRef = ref()
const formDlgData = reactive({
  tmName: '',
  logoUrl: '',
  id: '',
})
const tableData = ref<Records>([])
let pageNo = ref<number>(1)
let limit = ref<number>(3)
let total = ref<number>(0)
let dialogVisible = ref<boolean>(false)
const formRules = reactive<FormRules<RuleForm>>({
  tmName: [
    { required: true, message: '请输入品牌名称', trigger: 'blur' },
    { min: 3, max: 5, message: '3-5位', trigger: 'blur' },
  ],
  logoUrl: [{ required: true, message: '请上传图片', trigger: 'change' }],
})
const title = computed(() => {
  return formData?.id ? '修改' : '新增'
})

onMounted(() => {
  getTableData()
})

const getTableData = async (page = 1) => {
  pageNo.value = page

  const res: TradeMarkResponseData = await reqHasTrademark(
    pageNo.value,
    limit.value,
  )
  if (res.code == 200) {
    total.value = res.data.total || 0
    tableData.value = res.data.records || []
  }
}
const sizeChange = () => {
  getTableData()
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (response: any) => {
  formDlgData.logoUrl = response.data
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: any) => {
  const fileName = rawFile.name.split('.')
  const fileExt = fileName[fileName.length - 1]
  let ext = ['jpg', 'png', 'gif', 'bmp']
  const isTypeOk = ext.indexOf(fileExt) >= 0
  if (!isTypeOk) {
    ElNotification({
      type: 'warning',
      message: `上传图片只支持 ${ext.join(' / ')} 格式！`,
    })
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElNotification({
      type: 'warning',
      message: '不能大于2M',
    })
    return false
  }
  return true
}
const onAdd = () => {
  formDlgData.id = ''
  dialogVisible.value = true
}
const onEdit = (row: TradeMark) => {
  Object.assign(formDlgData, row)
  dialogVisible.value = true
}
const onDelete = async (id: number) => {
  let result = await reqDeleteTrademark(id)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getTableData(tableData.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}
const onSearch = () => {}

const submitDlg = async () => {
  await formDlgRef.value.validate()
  let result: ResponseData = await reqAddOrUpdateTrademark(formDlgData)
  if (result.code == 200) {
    handleClose()
    ElMessage({
      type: 'success',
      message: formDlgData.id ? '修改成功' : '新增成功',
    })
    getTableData(1)
  } else {
    ElMessage({
      type: 'error',
      message: formDlgData.id ? '修改失败' : '新增失败',
    })
    handleClose()
  }
}
const handleClose = () => {
  formDlgRef.value.resetFields()
  dialogVisible.value = false
}

const onReset = () => {
  formRef.value.resetFields()
}
</script>
<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
::v-deep .el-upload {
  border: 1px dotted #ccc;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
